package com.thiswhyme.ratelimiter.core;

import com.thiswhyme.ratelimiter.annotation.RateLimit;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * @description: 测试demo
 * @author: thiswhyme
 * @date: 2021/8/30
 */
@Slf4j
@Service
public class DemoService {

    @Autowired
    private LimitHandler limitHandler;

    public void doSomething1() {
        for (int i = 0; i < 100; i ++) {
            boolean acc = limitHandler.tryAccess("doSomething1", "333", 1, 1000);
            if (acc) {
                log.info("test do doSomething1...");
            } else {
                log.info("doSomething1限流了...");
            }
        }
    }

    @RateLimit(key = "doSomething2", subKey = "#param1 + \"-\" + #param2", rate = 2)
    public void doSomething2(String param1, String param2) {
        log.info("【{}-{}】test do doSomething2...", param1, param2);
    }

    @RateLimit(key = "doSomething3", subKey = "#param", rate = 1, rateIntervalMillis = 500, waitTimeoutMillis = 500)
    public void doSomething3(String param) {
        log.info("【{}】test do doSomethingAndWait...", param);
    }

    @RateLimit(key = "doSomething4", rate = 1, fallback = "doSomething4Fallback", dynamicRate = "${doSomething4.dynamicRate:2}")
    public String doSomething4(String param) {
        return "正常返回：" + param;
    }

    /**
     * doSomething4的自定义降级方法
     * @param param
     * @return
     */
    public String doSomething4Fallback(String param) {
        return "fallback返回：" + param;
    }
}
